// pages/order/order.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cartlist: [],
    data: {
      icons: 'edit',
      texts: '编辑'
    },
    totalprice: 0,
    selectAll: false,
    checkedIds: [],
    isLoading: false
  },

  /**
   * 切换编辑模式
   */
  setEdit() {
    const { data } = this.data;
    const newData = {
      icons: data.texts === '编辑' ? 'success' : 'edit',
      texts: data.texts === '编辑' ? '完成' : '编辑'
    };
    this.setData({ data: newData });
    console.log('当前模式:', newData.texts, '按钮文本:', newData.texts === '编辑' ? '结算' : '删除选中');
  },

  /**
   * 提交订单或删除
   */
  onSubmit() {
    const { texts } = this.data.data;
    const checkedItems = this.data.cartlist.filter(item => item.checked);
    
    if (checkedItems.length === 0) {
      this.showToast('请选择商品', 'none');
      return;
    }
    
    console.log('当前模式:', texts, '按钮文本:', texts === '编辑' ? '结算' : '删除选中');
    
    if (texts === '编辑') {
      // 编辑模式 -> 结算功能
      this.createOrder(checkedItems);
    } else {
      // 完成模式 -> 删除选中功能
      this.batchDeleteItems(checkedItems);
    }
  },

  /**
   * 结算功能
   */
  createOrder(checkedItems) {
    console.log('执行结算功能，选中商品:', checkedItems);
    
    // 这里实现结算逻辑
    if (checkedItems.length === 0) {
      this.showToast('请选择要结算的商品', 'none');
      return;
    }
    
    // 计算总价
    const totalAmount = checkedItems.reduce((total, item) => {
      return total + (item.price * item.number);
    }, 0);
    
    console.log('结算总价:', totalAmount);
    

    wx.showModal({
      title: '确认结算',
      content: `共 ${checkedItems.length} 件商品，总价 ¥${totalAmount.toFixed(2)}`,
      confirmText: '去支付',
      success: (res) => {
        if (res.confirm) {
          this.showToast('跳转到订单页面');
          wx.removeStorageSync('cartId');
          wx.removeStorageSync('addressId');
          wx.removeStorageSync('couponId');
          wx.removeStorageSync('grouponRulesId');
          wx.removeStorageSync('userCouponId');
          wx.navigateTo({
            url: '/pages/buys/comfirm'
          });
        }
      }
    });
  },

  /**
   * 批量删除商品
   */
  batchDeleteItems(checkedItems) {
    const productIds = checkedItems.map(item => item.productId);
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除选中的 ${productIds.length} 件商品吗？`,
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: 'http://admin.bsmall.byesame.com/wx/cart/delete',
            header: {
              'x-byesame-token': wx.getStorageSync('token')
            },
            data: { productIds: productIds },
            method: "POST",
            success: (res) => {
              if (res.data.errno === 0) {
                this.showToast('删除成功');
                this.getOrder();
              } else {
                this.showToast(res.data.errmsg || '删除失败', 'none');
              }
            },
            fail: (error) => {
              this.showToast('网络错误，请重试', 'none');
            }
          });
        }
      }
    });
  },

  /**
   * 获取购物车数据
   */
  getOrder() {
    wx.showLoading({ title: '加载中...' });
    
    wx.request({
      url: 'http://admin.bsmall.byesame.com/wx/cart/index',
      header: {
        'x-byesame-token': wx.getStorageSync('token')
      },
      method: "GET",
      success: (res) => {
        wx.hideLoading();
        if (res.data.errno === 0) {
          const cartList = res.data.data.cartList || [];
          const cartTotal = res.data.data.cartTotal || {};
          
          // 更新选中状态数组
          const checkedIds = cartList
            .filter(item => item.checked)
            .map(item => item.productId);
          
          // 判断是否全选
          const selectAll = cartList.length > 0 && cartList.every(item => item.checked);
          
          this.setData({
            cartlist: cartList,
            totalprice: cartTotal.checkedGoodsAmount || 0,
            checkedIds: checkedIds,
            selectAll: selectAll
          });
          console.log(res);
          console.log('购物车数据加载完成，当前模式:', this.data.data.texts);
        } else {
          this.showToast(res.data.errmsg || '加载失败', 'none');
        }
      },
      fail: (error) => {
        wx.hideLoading();
        console.error('加载购物车失败:', error);
        this.showToast('网络错误，请重试', 'none');
      }
    });
  },

  /**
   * 设置选中状态
   */
  setCheckedStatus(productIds, isChecked) {
    return new Promise((resolve, reject) => {
      if (this.data.isLoading) return;
      
      this.setData({ isLoading: true });
      
      wx.request({
        url: 'http://admin.bsmall.byesame.com/wx/cart/checked',
        header: {
          'x-byesame-token': wx.getStorageSync('token')
        },
        data: {
          isChecked: isChecked ? 1 : 0,
          productIds: productIds
        },
        method: "POST",
        success: (res) => {
          this.setData({ isLoading: false });
          if (res.data.errno === 0) {
            resolve(res.data);
          } else {
            reject(new Error(res.data.errmsg || '操作失败'));
          }
        },
        fail: (error) => {
          this.setData({ isLoading: false });
          reject(error);
        }
      });
    });
  },

  /**
   * 全选/取消全选
   */
  onSelectAllChange(e) {
    const isSelected = e.detail;
    const productIds = this.data.cartlist.map(item => item.productId);
    
    this.setCheckedStatus(productIds, isSelected)
      .then(() => {
        this.setData({ selectAll: isSelected });
        this.getOrder();
        this.showToast(isSelected ? '已全选' : '已取消全选');
      })
      .catch((error) => {
        console.error('全选操作失败:', error);
        this.showToast(error.message || '操作失败', 'none');
        this.setData({ selectAll: !isSelected });
      });
  },

  /**
   * 单个商品选中状态改变
   */
  onCheckChange(e) {
    const { id, checked } = e.currentTarget.dataset;
    const newCheckedState = !checked;
    
    this.setCheckedStatus([id], newCheckedState)
      .then(() => {
        this.getOrder();
      })
      .catch((error) => {
        console.error('选中状态修改失败:', error);
        this.showToast(error.message || '操作失败', 'none');
      });
  },

  /**
   * 修改商品数量
   */
  onNumberChange(e) {
    const { goodsid, id, productid } = e.currentTarget.dataset;
    console.log(e);
    const number = e.detail;
    
    wx.request({
      url: 'http://admin.bsmall.byesame.com/wx/cart/update',
      header: {
        'x-byesame-token': wx.getStorageSync('token')
      },
      data: {
        goodsId: goodsid,
        id: id,
        productId: productid,
        number: number
      },
      method: "POST",
      success: (res) => {
        // console.log(goodsId);
        console.log(res);
        if (res.data.errno === 0) {
          
          this.getOrder();
        } else {
          this.showToast(res.data.errmsg || '更新失败', 'none');
          this.getOrder(); // 刷新数据恢复正确数量
        }
      },
      fail: (error) =>{
        console.error('更新数量失败:', error);
        this.showToast('网络错误，请重试', 'none');
        this.getOrder();
      }
    });
  },

  /**
   * 删除单个商品
   */
  onDeleteItem(e) {
    const productId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个商品吗？',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          this.deleteCartItem(productId);
        }
      }
    });
  },

  deleteCartItem(productId) {
    wx.request({
      url: 'http://admin.bsmall.byesame.com/wx/cart/delete',
      header: {
        'x-byesame-token': wx.getStorageSync('token')
      },
      data: { productIds: [productId] },
      method: "POST",
      success: (res) => {
        if (res.data.errno === 0) {
          this.showToast('删除成功');
          this.getOrder();
        } else {
          this.showToast(res.data.errmsg || '删除失败', 'none');
        }
      },
      fail: (error) => {
        console.error('删除失败:', error);
        this.showToast('网络错误，请重试', 'none');
      }
    });
  },

  /**
   * 显示提示
   */
  showToast(message, icon = 'success') {
    wx.showToast({
      title: message,
      icon: icon,
      duration: 2000
    });
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.showToast('请先登录', 'none');
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return false;
    }
    return true;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (this.checkLoginStatus()) {
      this.getOrder();
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.checkLoginStatus()) {
      this.getOrder();
    }
  }
});